package com.csi.okr.common.util;

    import org.apache.http.HttpResponse;
    import org.apache.http.HttpStatus;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.message.BasicNameValuePair;
    import org.apache.http.params.BasicHttpParams;
    import org.apache.http.params.HttpConnectionParams;
    import org.apache.http.params.HttpParams;
    import org.apache.http.util.EntityUtils;

import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

public class HttpRequestUtil {

    /**
     * 发送get请求
     */
    @SuppressWarnings("restriction")
    public static String sendGet(String url) {
        String r = "";
        BufferedReader in = null;
        try {
            String urlNameString = url;
//			URL realUrl = new URL(urlNameString);
            //重点在这里，需要使用带有URLStreamHandler参数的URL构造方法
            URL realUrl = new URL(null, urlNameString, new sun.net.www.protocol.https.Handler());
            //由于我调用的是官方给微信API接口，所以采用HTTPS连接
            HttpsURLConnection connection = (HttpsURLConnection) realUrl.openConnection();
//			int responseCode = connection.getResponseCode();

            // 打开和URL之间的连接
//			URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                r += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return r;
    }

    @SuppressWarnings({"resource", "rawtypes"})
    public static String sendPost(String url, Map<String, Object> params) {

        HttpClient httpClient = null;
        try {
            HttpParams httpParams = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
            HttpConnectionParams.setSoTimeout(httpParams, 10000);
            httpClient = new DefaultHttpClient(httpParams);

            HttpPost post = null;

            post = new HttpPost(url);

            List<NameValuePair> param = new ArrayList<NameValuePair>();
            Set set = params.keySet();
            for (Iterator iter = set.iterator(); iter.hasNext(); ) {
                String key = (String) iter.next();
                String value = params.get(key) + "";
                System.out.println(key + ":" + value);
                param.add(new BasicNameValuePair(key, value));
            }

            post.setEntity(new UrlEncodedFormEntity(param, "UTF-8"));

            HttpResponse response = httpClient.execute(post);

            if (response != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

                byte[] bytes = null;
                String result = null;
                try {
                    bytes = EntityUtils.toByteArray(response.getEntity());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    result = new String(bytes, "UTF-8");

                    return result;

                } catch (Exception e) {

                    return null;
                }
            } else {

                return response.getStatusLine().getStatusCode() + "";
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            httpClient.getConnectionManager().shutdown();
        }
        return null;
    }

    public static String sendPost(String url, String Params){
        OutputStreamWriter out = null;
        BufferedReader reader = null;
        String response = "";
        try {
            URL httpUrl = null; //HTTP URL类 用这个类来创建连接
            //创建URL
            httpUrl = new URL(url);
            //建立连接
            HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("connection", "keep-alive");
            conn.setUseCaches(false);//设置不要缓存
            conn.setInstanceFollowRedirects(true);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.connect();
            //POST请求
            out = new OutputStreamWriter(
                    conn.getOutputStream());
            out.write(Params);
            out.flush();
            //读取响应
            reader = new BufferedReader(new InputStreamReader(
                    conn.getInputStream()));
            String lines;
            while ((lines = reader.readLine()) != null) {
                lines = new String(lines.getBytes(), "utf-8");
                response += lines;
            }
            reader.close();
            // 断开连接
            conn.disconnect();

        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        return response;
    }

}
